﻿using System.Collections.Generic;

namespace DimensionsHelper.Services.DataTable;

public enum DataRowKind
{
    /// <summary>
    ///     普通数据行
    /// </summary>
    Normal,

    /// <summary>
    ///     基数数据行
    /// </summary>
    Base,

    /// <summary>
    ///     小计数据行
    /// </summary>
    Subtotal,

    /// <summary>
    ///     平均值数据行，即 Subtotal / RowsCount
    /// </summary>
    Average,

    /// <summary>
    ///     平均平均数，即 Subtotal / Base
    /// </summary>
    SampleAverage
}

public class SampleDataRow(SampleDataTable table, int rowIndex, string header)
{
    private readonly List<SampleDataCell> _cells = [];

    /// <summary>
    ///     当前数据行的类型
    /// </summary>
    public DataRowKind Kind { get; internal set; } = DataRowKind.Normal;

    /// <summary>
    ///     获取指定索引的行单元格，如果不存在，将创建新的。
    /// </summary>
    /// <param name="index">列索引，0开始</param>
    /// <returns>指定索引的行单元格</returns>
    public SampleDataCell this[int index]
    {
        get
        {
            table.EnsureColumnCapacityInternal(index + 1);
            EnsureCapacity(index + 1);
            return _cells[index];
        }
    }

    /// <summary>
    ///     获取指定列名所在位置的行单元格，如果不存在，将创建新的。
    /// </summary>
    /// <param name="columnName">列名</param>
    /// <returns>指定列名所在位置的行单元格</returns>
    public SampleDataCell this[string columnName]
    {
        get
        {
            var col = table.GetColumn(columnName);
            EnsureCapacity(col.ColumnIndex + 1);
            return _cells[col.ColumnIndex];
        }
    }

    /// <summary>
    ///     当前行在数据表中的索引，0开始。
    /// </summary>
    public int RowIndex { get; set; } = rowIndex;

    /// <summary>
    ///     当前行的行头，默认是<see cref="string.Empty" />
    /// </summary>
    public string Header { get; } = header;

    /// <summary>
    ///     当前行的位置是否固定。
    /// </summary>
    public bool IsFixedPosition =>
        Kind == DataRowKind.Base
        || Kind == DataRowKind.Subtotal
        || Kind == DataRowKind.Average
        || Kind == DataRowKind.SampleAverage;

    /// <summary>
    ///     当前行是否不保存样本。
    /// </summary>
    public bool NoSample => Kind == DataRowKind.Subtotal || Kind == DataRowKind.Average ||
                            Kind == DataRowKind.SampleAverage;

    internal void EnsureCapacity(int capacity)
    {
        var i = _cells.Count;
        while (i < capacity)
        {
            _cells.Add(new SampleDataCell(this, table.GetColumn(i), table));
            i++;
        }
    }

    /// <summary>
    ///     移除指定位置的行单元格
    /// </summary>
    /// <param name="index">指定含单元格索引</param>
    internal void RemoveAt(int index)
    {
        _cells.RemoveAt(index);
    }

    /// <summary>
    ///     清空行单元格内容。
    /// </summary>
    public void Clear()
    {
        _cells.Clear();
    }
}